<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Think\Controller;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;

/**
 * 行为控制器
 * @author huajie <banhuajie@163.com>
 */
class TestController extends Controller
{
    function test()
    {
        date_default_timezone_set("Asia/Shanghai");
        $time = intval(date("i"));

        $this->query_split();
        $this->divide();
        $this->delete();
        $this->trans();
        // $this->trans2();
//         $this->transToAlipay();


        if ($time % 5 == 0) {
            $this->youka_check();
        }

    }

    /**
     * 从收款支付宝转账到企业支付宝
     */
    public function transToAlipay()
    {
        // 所有状态0的订单  利用查询接口查看是否已成功
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $transfer = new \Alipay;
        $list = D('Trans')->where(['status' => 0, 'count' => 0])->select();
        // print_r($list);die;
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $money = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        foreach ($list as $key => $v) {
            if (preg_match('/^[hxft]/', $v['out_biz_no'])) {

                $ptyh = D('Ptyh')->where(['uid' => $v['uid']])->find();
                $alipay = $v['buyer_id'];
                $amount = $v['money'] - 2; // 2元手续费
                $out_biz_no = $v['out_biz_no'];
                $remark = "转账";
                $payer_show_name = $ptyh['name'];
                // 查看当日提现总金额  超过95万则使用另一个支付宝
//                $adata = D('Adata')->where(['id' => 1])->find();
//                $shoukuan = M('shouquan')->find();
                $alipays = M('alipays')->where(['status' => 1, 'type' => 1])->find();

                //收款账号转账给付款人
                $result = $transfer->transferSingleAlipay($out_biz_no, $alipay, $amount, $remark, $payer_show_name, $alipays);
                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'transToAlipay回款结果: '. json_encode($result) . PHP_EOL, FILE_APPEND);

                if (empty($result->sub_msg) && $result->out_biz_no == $out_biz_no) {
                    // 说明是成功的
                    $trade_num = $result->order_id;
                    $time = $result->pay_date;
                    D('Trans')->where("out_biz_no='{$out_biz_no}'")->save(['status' => 1, 'trade_num' => $trade_num, 'out_biz_no' => $out_biz_no, 'time' => $time, 'count' => 1]);

                    //支付成功提醒
                    $one = D('Dingdan')->where(['trade_no' => $v['trade_no']])->find();
                    $money = $one['yh_money'];
                    $data = [
                        'money' => $one['pay_money'],
                        'time' => date("Y-m-d H:i:s", $one['pay_time']), //应当填写结算时间
                        'remark' => "收款订单号：" . $one['danhao'] . '，收益金额：' . $money . '，付款方：' . $one['buyer'],
                    ];

                    $member = D('Ptyh')->where(['uid' => $one['uid']])->find();
                    if (!empty($member)) {
                        D('Notice')->weixin(10, $member['wx_uid'], $data);
                    } else {
                        // echo '未绑定微信';die;
                    }

                } else {
                    if ($result->sub_code == 'PAYCARD_UNABLE_PAYMENT') {
                        D('Tongdao')->save(['hk_hb' => 0, 'hk_fq' => 0]);
                    }
                    $cause = 'code: '.$result->sub_code . ',msg: ' . $result->sub_msg;
                    D('Trans')->where("out_biz_no='{$out_biz_no}'")->save(['cause' => $cause, 'count' => 1]);
                }
            }
        }
    }

    /**
     * 花呗分账方法
     */
    function query_split()
    {
        // 查询分账表 未完成交易的
        $split = D('Split')->where('status=0')->select();
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $qrpay = new \Alipay;

        foreach ($split as $key => $v) {
            $seller_id = $v['seller_id'];
            $kbsh = D('Kbsh')->where('user_id=' . $seller_id)->find();

            $kbxx = D('Kbxx')->where('uid=' . $kbsh['uid'])->find();
            $app_auth_token = $kbsh['app_auth_token'];

            // echo '1//';
            // print_r($kbsh);
            $money_out = $v['money_in'] * (1 - $kbsh['rate2'] / 100);//需要进行分账的金额  比总金额少
            $money_out = round($money_out, 2);   //两位小数  四舍五入


            $trade_no = $v['trade_no'];                         //需要进行分账的当比订单号    2017121521001004820275153639

            $time = time();       //进行分账的时间
            $out_request_no = '';
            $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号
            $data = [
                'out_request_no' => $out_request_no,
                'money_out' => $money_out,
                'sh_money' => $v['money_in'] * ($kbsh['rate'] - $kbsh['rate2']) / 100,
                'time' => $time,
                'name' => $kbxx['name'],
                'uid' => $kbxx['uid'],
            ];
            // echo '2//';
            // print_r($data);
            // 修改
//            $adata = D('Adata')->where(['id' => 1])->find();

            $toAccount = D('Adata')->where(['id' => 1])->find();
            $adata = M('shouquan')->find();


            D('Split')->where("trade_no='{$trade_no}'")->save($data);
            $royalty_parameters = [
                'trans_out' => "{$seller_id}",//分账出去的user_id
                'trans_in' => $toAccount['t_account'],

                'amount' => $money_out,   //分账出去的金额
                'desc' => '绿叶收银台服务中心-分账',
            ];
            // print_r($royalty_parameters);die;
            // // 调用线下收单结算接口
//            file_put_contents("hb.txt", date('Y-m-d H:i:s').'split调用线下收单接口参数: '. json_encode([$out_request_no, $trade_no, $royalty_parameters, $app_auth_token, $adata]) . PHP_EOL, FILE_APPEND);

            $result = $qrpay->settle($out_request_no, $trade_no, $royalty_parameters, $app_auth_token, $adata);
            // print_r($result);
            // $arr[]=$result;
//            file_put_contents("hb.txt", date('Y-m-d H:i:s').'split调用线下收单接口结果: '. json_encode($result) . PHP_EOL, FILE_APPEND);

            if ($result->trade_no == $trade_no && empty($result->sub_msg)) {
                // 修改
                D('Split')->where("trade_no='{$trade_no}'")->save(['status' => 1]);
                // 增加余额
                $gather = D('Gather')->where('uid=' . $kbsh['uid'])->find();
                $money = $gather['money'] + $v['money_in'] * ($kbsh['rate'] - $kbsh['rate2']) / 100;
                $gather = D('Gather')->where('uid=' . $kbsh['uid'])->save(['money' => $money]);
                D('Split')->where('id=' . $v['id'])->save(['t_money' => $money, 'sub_msg' => '']);

            } else {
                $sub_msg = $result->sub_msg;
                if ($sub_msg == '接口返回错误') {
                    D('Kbsh')->where('user_id=' . $seller_id)->save(['use_status' => 0, 'cause' => $sub_msg . '//余额关闭', 'money' => $money_out]);
                    D('Split')->where("trade_no='{$trade_no}'")->save(['status' => 1, 'sub_msg' => $sub_msg . '//已下架']);
                } else {
                    D('Split')->where("trade_no='{$trade_no}'")->save(['sub_msg' => $sub_msg]);
                }

            }
            // die;
        }


    }

    function query_split_(){
        // 查询分账表 未完成交易的
        $split=D('Split')->where('status=0')->select();

        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $qrpay= new \Alipay;

        foreach ($split as $key => $v) {
            $seller_id=$v['seller_id'];
            $kbsh=D('Kbsh')->where('user_id='.$seller_id)->find();

            $kbxx=D('Kbxx')->where('uid='.$kbsh['uid'])->find();
            $app_auth_token   =  $kbsh['app_auth_token'];
            // echo '1//';
            // print_r($kbsh);
            $money_out=$v['money_in']*(1-$kbsh['rate2']/100);//需要进行分账的金额  比总金额少
            $money_out=round($money_out, 2);   //两位小数  四舍五入
            $trade_no=$v['trade_no'];  //需要进行分账的当比订单号    2017121521001004820275153639

            $time=time();       //进行分账的时间
            $out_request_no='';
            $out_request_no=date("Ymd").rand(1000000000,9999999999);  //分账流水号
            $data=[
                'out_request_no'=>$out_request_no,
                'money_out'    =>$money_out,
                'sh_money'     =>$v['money_in']*($kbsh['rate']-$kbsh['rate2'])/100,
                'time'          =>$time,
                'name'         =>$kbxx['name'],
                'uid'         =>$kbxx['uid'],
            ];
            // echo '2//';
            // print_r($data);
            // 修改
            $adata=D('Adata')->where(['id'=>1])->find();
            D('Split')->where("trade_no='{$trade_no}'")->save($data);
            $royalty_parameters=[
                'trans_out'        =>"{$seller_id}",//分账出去的user_id
                'trans_in'         =>$adata['t_account'],
                // 'trans_in'         =>'2088721894960112',
                'amount'           =>$money_out,   //分账出去的金额
                'desc'             =>'绿叶收银台服务中心-分账',
            ];
            // print_r($royalty_parameters);die;
            // // 调用线下收单结算接口
            $result=$qrpay->settle($out_request_no,$trade_no,$royalty_parameters,$app_auth_token,$adata);
            // print_r($result);
            // $arr[]=$result;
            if($result->trade_no==$trade_no&&empty($result->sub_msg)){

                // 修改
                D('Split')->where("trade_no='{$trade_no}'")->save(['status'=>1]);

                // 增加余额
                $gather=D('Gather')->where('uid='.$kbsh['uid'])->find();
                $money=$gather['money']+$v['money_in']*($kbsh['rate']-$kbsh['rate2'])/100;
                $gather=D('Gather')->where('uid='.$kbsh['uid'])->save(['money'=>$money]);
                D('Split')->where('id='.$v['id'])->save(['t_money'=>$money,'sub_msg'=>'']);

            }else{
                $sub_msg=$result->sub_msg;
                if($sub_msg=='接口返回错误'){
                    D('Kbsh')->where('user_id='.$seller_id)->save(['use_status'=>0,'cause'=>$sub_msg.'//余额关闭','money'=>$money_out]);
                    D('Split')->where("trade_no='{$trade_no}'")->save(['status'=>1,'sub_msg'=>$sub_msg.'//已下架']);
                }else{
                    D('Split')->where("trade_no='{$trade_no}'")->save(['sub_msg'=>$sub_msg]);
                }

            }
            // die;
        }


    }


    public function delete()
    {
        $list = D('Gather')->select();
        foreach ($list as $key => $v) {
            $uid = $v['uid'];

            $one = D('Ptyh')->where(['uid' => $uid])->find();
            if (empty($one) || empty($one['identify'])) {
                // 没有这个平台用户
                D('Gather')->where(['uid' => $uid])->delete();
            } else {
                $re = D('Gather')->where(['uid' => $uid])->select();
                if (count($re) > 1) {
                    // 如果数据库有多余的  删除其他 只剩ID最小的一条
                    unset($re[0]);
                    foreach ($re as $key => $va) {

                        D('Gather')->where("id=$va[id]")->delete();
                    }
                }
            }

        }


    }

    /**
     * 自动回款 -- 打款给付款人
     */
    public function trans()
    {
        // 所有状态0的订单  利用查询接口查看是否已成功
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $transfer = new \Alipay;
        $list = D('Trans')->where(['status' => 0, 'count' => 0])->select();
        // print_r($list);die;
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $money = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        foreach ($list as $key => $v) {
            if (preg_match('/^[hxft]/', $v['out_biz_no'])) {

                $ptyh = D('Ptyh')->where(['uid' => $v['uid']])->find();
                $alipay = $v['buyer_id'];
                $amount = $v['money'] - 3; // 3元手续费
                $out_biz_no = $v['out_biz_no'];
                $remark = "转账";
                $payer_show_name = $ptyh['name'];
                // 查看当日提现总金额  超过95万则使用另一个支付宝
//                $adata = D('Adata')->where(['id' => 1])->find();
                $alipays = M('alipays')->where(['status' => 1, 'type' => 1])->find();

                //adata中tx_appid
                $result = $transfer->transferXyk($out_biz_no, $alipay, $amount, $remark, $payer_show_name, $alipays);
//                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'trans回款结果1: '. json_encode($result) . PHP_EOL, FILE_APPEND);

                if (empty($result->sub_msg) && $result->out_biz_no == $out_biz_no) {

                    // 说明是成功的
                    $trade_num = $result->order_id;
                    $time = $result->pay_date;
                    D('Trans')->where("out_biz_no='{$out_biz_no}'")->save(['status' => 1, 'trade_num' => $trade_num, 'out_biz_no' => $out_biz_no, 'time' => $time, 'count' => 1]);

                    //支付成功提醒
                    $one = D('Dingdan')->where(['trade_no' => $v['trade_no']])->find();
                    $money = $one['yh_money'];
                    $data = [
                        'money' => $one['pay_money'],
                        'time' => date("Y-m-d H:i:s", $one['pay_time']), //应当填写结算时间
                        'remark' => "收款订单号：" . $one['danhao'] . '，收益金额：' . $money . '，付款方：' . $one['buyer'],
                    ];

                    $member = D('Ptyh')->where(['uid' => $one['uid']])->find();
                    if (!empty($member)) {
                        D('Notice')->weixin(10, $member['wx_uid'], $data);
                    } else {
                        // echo '未绑定微信';die;
                    }

                } else {
                    if ($result->sub_code == 'PAYCARD_UNABLE_PAYMENT') {
                        D('Tongdao')->save(['hk_hb' => 0, 'hk_fq' => 0]);
                    }
                    $cause = $result->sub_msg;
                    D('Trans')->where("out_biz_no='{$out_biz_no}'")->save(['cause' => $cause, 'count' => 1]);
                }


                //信用卡 二次转账给企业支付宝
                if(strpos($out_biz_no,'xy') !== false){
                    //信用卡
                    $out_biz_no = 'xy' . date("YmdHis") . rand(1000, 9999);
                    $adata = D('Adata')->where(['id' => 1])->find();
                    $remark = '信用卡二次转账给支付宝';
                    //订单金额×（回款费率－成本费率）＋3（信用卡的3元手续费）
                    $shoukuanma = M('shoukuanma')->where(['id' => $v['shoukuanma_id']])->find();
                    $alipays = M('alipays')->where(['status' => 1, 'type' => 1])->find();
                    $amount = $v['account']*($shoukuanma['xyk'] - $alipays['chengben'])/100 + 3;
                    $amount = number_format(floor($amount * 100) / 100, 2, '.', '');
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . ' 信用卡二次转账金额：' . $amount . PHP_EOL, FILE_APPEND);

                    $xyktwo = $transfer->transferXyk($out_biz_no, $adata['t_account'], $amount, $remark, $payer_show_name, $alipays);
                    if (empty($xyktwo->sub_msg) && $xyktwo->out_biz_no == $out_biz_no) {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . ' 信用卡二次转账给支付宝成功：' . PHP_EOL, FILE_APPEND);

                    }else{
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . ' 信用卡二次转账给支付宝失败，原因：' .$xyktwo->sub_msg . ' --out_biz_no: '.  $out_biz_no . PHP_EOL, FILE_APPEND);
                    }
                }




            }
        }
    }

    /**
     * 自动回款 -- 打款给付款人
     */
    public function trans_()
    {
        // 所有状态0的订单  利用查询接口查看是否已成功
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $transfer = new \Alipay;
        $list = D('Trans')->where(['status' => 0, 'count' => 0])->select();
        // print_r($list);die;
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $money = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        foreach ($list as $key => $v) {
            if (preg_match('/^[hxft]/', $v['out_biz_no'])) {

                $ptyh = D('Ptyh')->where(['uid' => $v['uid']])->find();
                $alipay = $v['buyer_id'];
                $amount = $v['money'] - 3; // 3元手续费
                $out_biz_no = $v['out_biz_no'];
                $remark = "转账";
                $payer_show_name = $ptyh['name'];
                // 查看当日提现总金额  超过95万则使用另一个支付宝
                $adata = D('Adata')->where(['id' => 1])->find();

                //adata中tx_appid
                $result = $transfer->transfer5($out_biz_no, $alipay, $amount, $remark, $payer_show_name, $adata);
//                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'trans回款结果1: '. json_encode($result) . PHP_EOL, FILE_APPEND);

                //信用卡 二次转账给企业支付宝
                if(strpos($out_biz_no,'xy') !== false){
                    //信用卡
                    $adata = D('Adata')->where(['id' => 1])->find();
                    $remark = '信用卡二次转账给支付宝';
                    //订单金额×（回款费率－成本费率）＋3（信用卡的3元手续费）
                    $shoukuanma = M('shoukuanma')->where(['id' => $v['shoukuanma_id']])->find();
                    $alipays = M('alipays')->where(['status' => 1, 'type' => 1])->find();
                    $amount = $v['money']*($shoukuanma['xyk'] - $alipays['chengben']) + 3;
                    $xyktwo = $transfer->transfer5($out_biz_no, $adata['t_account'], $amount, $remark, $payer_show_name, $adata);



                }else{
                    if (empty($result->sub_msg) && $result->out_biz_no == $out_biz_no) {
                        // 说明是成功的
                        $trade_num = $result->order_id;
                        $time = $result->pay_date;
                        D('Trans')->where("out_biz_no='{$out_biz_no}'")->save(['status' => 1, 'trade_num' => $trade_num, 'out_biz_no' => $out_biz_no, 'time' => $time, 'count' => 1]);

                        //支付成功提醒
                        $one = D('Dingdan')->where(['trade_no' => $v['trade_no']])->find();
                        $money = $one['yh_money'];
                        $data = [
                            'money' => $one['pay_money'],
                            'time' => date("Y-m-d H:i:s", $one['pay_time']), //应当填写结算时间
                            'remark' => "收款订单号：" . $one['danhao'] . '，收益金额：' . $money . '，付款方：' . $one['buyer'],
                        ];

                        $member = D('Ptyh')->where(['uid' => $one['uid']])->find();
                        if (!empty($member)) {
                            D('Notice')->weixin(10, $member['wx_uid'], $data);
                        } else {
                            // echo '未绑定微信';die;
                        }

                    } else {
                        if ($result->sub_code == 'PAYCARD_UNABLE_PAYMENT') {
                            D('Tongdao')->save(['hk_hb' => 0, 'hk_fq' => 0]);
                        }
                        $cause = $result->sub_msg;
                        D('Trans')->where("out_biz_no='{$out_biz_no}'")->save(['cause' => $cause, 'count' => 1]);
                    }
                }




            }
        }
    }

    // 分润
    public function divide()
    {
        $list = D('Dividend')->where(['status' => 0])->select();

        foreach ($list as $key => $value) {
            $trade_no = $value['trade_no'];
            $re = D('Dividend')->where(['trade_no' => $trade_no])->select();
            if (count($re) > 1) {
                // 如果数据库有多余的  删除其他 只剩ID最小的一条
                unset($re[0]);
                foreach ($re as $key => $va) {

                    D('Dividend')->where("id=$va[id]")->delete();
                }
            }
        }
        foreach ($list as $key => $v) {
            $uid = intval($v['shou']);
            $time = time();

            $c1 = D('Ptyh')->where("uid={$uid}")->find(); //当前订单用户
            $g1 = D('Gather')->where("uid={$uid}")->find(); //当前订单用户


            if ($c1['level'] == 4) {
                $pid1 = intval($v['parent']);
                $shou1 = $c1['name'] . '-' . $c1['shop_name'];
                $p1 = D('Ptyh')->where("uid={$pid1}")->find();//上级
                $parent1 = $p1['name'] . '-' . $p1['shop_name'];
                $g2 = D('Gather')->where("uid={$pid1}")->find();


                $pid2 = $p1['pid'];
                $p2 = D('Ptyh')->where("uid={$pid2}")->find();//上上级
                $parent2 = $p2['name'] . '-' . $p2['shop_name'];
                $g3 = D('Gather')->where("uid={$pid2}")->find();


                $pid3 = $p2['pid'];
                $p3 = D('Ptyh')->where("uid={$pid3}")->find();//上上上级
                $parent3 = $p3['name'] . '-' . $p3['shop_name'];
                $g4 = D('Gather')->where("uid={$pid3}")->find();


                if (preg_match('/^[hft]/', $v['danhao'])) {
                    $divide1 = ($g1['up_set'] - $g2['up_set']) / 100 * $v['total'];
                    $divide2 = ($g2['up_set'] - $g3['up_set']) / 100 * $v['total'];
                    $divide3 = ($g3['up_set'] - $g4['up_set']) / 100 * $v['total'];
                } else {
                    $divide1 = ($g1['up_set2'] - $g2['up_set2']) / 100 * $v['total'];
                    $divide2 = ($g2['up_set2'] - $g3['up_set2']) / 100 * $v['total'];
                    $divide3 = ($g3['up_set2'] - $g4['up_set2']) / 100 * $v['total'];
                }


                $data1 = array(
                    'shou' => $shou1,
                    'parent' => $parent1,
                    'divide' => $divide1,
                    'time' => $time,
                    'status' => 1,
                    't_money' => $g2['money'] + $divide1,
                );
                $data2 = array(
                    'uid' => $p2['uid'],
                    'trade_no' => $v['trade_no'],
                    'total' => $v['total'],
                    'danhao' => $v['danhao'],
                    'shou' => $shou1,
                    'parent' => $parent2,
                    'divide' => $divide2,
                    'time' => $time,
                    'status' => 1,
                    't_money' => $g3['money'] + $divide2,
                );
                $data3 = array(
                    'uid' => $p3['uid'],
                    'trade_no' => $v['trade_no'],
                    'total' => $v['total'],
                    'danhao' => $v['danhao'],
                    'shou' => $shou1,
                    'parent' => $parent3,
                    'divide' => $divide3,
                    'time' => $time,
                    'status' => 1,
                    't_money' => $g4['money'] + $divide3,
                );


                D('Dividend')->where("id={$v[id]}")->save($data1);
                D('Dividend')->add($data2);
                D('Dividend')->add($data3);
                D('Gather')->where(['uid' => $pid1])->setInc('money', $divide1);
                D('Gather')->where(['uid' => $pid2])->setInc('money', $divide2);
                D('Gather')->where(['uid' => $pid3])->setInc('money', $divide3);

            } else if ($c1['level'] == 3) {
                $pid1 = intval($v['parent']);
                $shou1 = $c1['name'] . '-' . $c1['shop_name'];
                $p1 = D('Ptyh')->where("uid={$pid1}")->find();//上级
                $parent1 = $p1['name'] . '-' . $p1['shop_name'];
                $g2 = D('Gather')->where("uid={$pid1}")->find();


                $pid2 = $p1['pid'];
                $p2 = D('Ptyh')->where("uid={$pid2}")->find();//上上级
                $parent2 = $p2['name'] . '-' . $p2['shop_name'];
                $g3 = D('Gather')->where("uid={$pid2}")->find();


                if (preg_match('/^[hft]/', $v['danhao'])) {
                    $divide1 = ($g1['up_set'] - $g2['up_set']) / 100 * $v['total'];
                    $divide2 = ($g2['up_set'] - $g3['up_set']) / 100 * $v['total'];
                } else {
                    $divide1 = ($g1['up_set2'] - $g2['up_set2']) / 100 * $v['total'];
                    $divide2 = ($g2['up_set2'] - $g3['up_set2']) / 100 * $v['total'];
                }


                $data1 = array(
                    'shou' => $shou1,
                    'parent' => $parent1,
                    'divide' => $divide1,
                    'time' => $time,
                    'status' => 1,
                    't_money' => $g2['money'] + $divide1,
                );
                $data2 = array(
                    'uid' => $p2['uid'],
                    'trade_no' => $v['trade_no'],
                    'total' => $v['total'],
                    'danhao' => $v['danhao'],
                    'shou' => $shou1,
                    'parent' => $parent2,
                    'divide' => $divide2,
                    'time' => $time,
                    'status' => 1,
                    't_money' => $g3['money'] + $divide2,
                );


                D('Dividend')->where("id={$v[id]}")->save($data1);
                D('Dividend')->add($data2);
                D('Gather')->where(['uid' => $pid1])->setInc('money', $divide1);
                D('Gather')->where(['uid' => $pid2])->setInc('money', $divide2);

            } else if ($c1['level'] == 2) {
                $pid1 = intval($v['parent']);
                $shou1 = $c1['name'] . '-' . $c1['shop_name'];
                $p1 = D('Ptyh')->where("uid={$pid1}")->find();//上级
                $parent1 = $p1['name'] . '-' . $p1['shop_name'];
                $g2 = D('Gather')->where("uid={$pid1}")->find();


                if (preg_match('/^[hft]/', $v['danhao'])) {
                    $divide1 = ($g1['up_set'] - $g2['up_set']) / 100 * $v['total'];
                } else {
                    $divide1 = ($g1['up_set2'] - $g2['up_set2']) / 100 * $v['total'];
                }


                $data1 = array(
                    'shou' => $shou1,
                    'parent' => $parent1,
                    'divide' => $divide1,
                    'time' => $time,
                    'status' => 1,
                    't_money' => $g2['money'] + $divide1,
                );


                D('Dividend')->where("id={$v[id]}")->save($data1);
                D('Gather')->where(['uid' => $pid1])->setInc('money', $divide1);

            }


        }
    }


    function up_down()
    {
        $list = D('Gather')->select();
        $arr = array();
        foreach ($list as $key => $v) {
            $yh = D('Ptyh')->where(['uid' => $v['uid']])->find();
            if ($yh['level'] != $v['level']) {
                if ($yh['level'] == 1) {
                    $up_set = 1.5;
                } else if ($yh['level'] == 2) {
                    $up_set = 2;
                } else if ($yh['level'] == 3) {
                    $up_set = 2.5;
                } else if ($yh['level'] > 3) {
                    $up_set = 3;
                }
                print_r($yh);
                print_r($v);
                // D('Gather')->where(['uid'=>$v['uid']])->save(['level'=>$yh['level'],'up_set'=>$up_set]);
            }

        }


    }


    function youka_check()
    {
        $account = '15518311221';

//         $one=D('Youka')->where(['orderId'=>'20180313113138383181'])->find();
//                     $ga=D('Gather')->where(['uid'=>$one['uid']])->find();
//                     $t_money=$ga['money']+$one['yh_money'];
//                     D('Gather')->where(['uid'=>$one['uid']])->save(['money'=>$t_money]);
//                     D('Youka')->where(['orderId'=>$one['orderId']])->save(['t_money'=>$t_money]);
//         echo D('Gather')->getlastsql();
// echo D('Youka')->getlastsql();
//         die;
        $list = D('Youka')->where(['re_status' => 0])->select();
        foreach ($list as $key => $v) {

            $json = array(
                'account' => $account,
                'orderId' => $v['orderId'],
            );
            $sign = '';
            foreach ($json as $key => $va) {
                $sign .= $key . $va;
            }
            $sign = $sign . 'eec62b20c54142188bfad1460ca6c691';
            $json['sign'] = md5($sign);
            $url = 'http://api.jiayouka.cn:11140/userApi/supply/queryOrder';
            $res = $this->send_request($url, $json);

            if ($res['code'] == '10010') {

                //1 核销成功  0  处理中 2 核销失败


                if ($res['state'] == 1) {
                    // 核销成功且存储成功后，增加余额记录余额
                    $ga = D('Gather')->where(['uid' => $v['uid']])->find();
                    $t_money = $ga['money'] + $v['yh_money'];

                    D('Youka')->where(['orderId' => $v['orderId']])->save(['re_status' => 1, 't_money' => $t_money]);
                    D('Gather')->where(['uid' => $v['uid']])->save(['money' => $t_money]);

                } else if ($res['state'] == 2) {
                    D('Youka')->where(['orderId' => $v['orderId']])->save(['re_status' => 2]);
                }


            }
        }
    }


    function send_request($request, $params, $method = 'get', $https = false)
    {
        // 以get方式提交
        if ($method == 'get') {
            $request = $request . $this->create_url($params);
        }

        // return $request;

        $this->ch = curl_init($request);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);// 设置不显示结果，储存入变量
        // curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT); // 设置超时限制防止死循环

        // 判断是否以https方式访问
        if ($https) {
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        }

        if ($method == 'post') {        // 以post方式提交
            curl_setopt($this->ch, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params); // Post提交的数据包
        }

        $tmpInfo = curl_exec($this->ch); // 执行操作
        if (curl_errno($this->ch)) {
            echo 'Errno:' . curl_error($this->ch);//捕抓异常
        }
        curl_close($this->ch); // 关闭CURL会话
        return json_decode($tmpInfo, true);
        return $tmpInfo; // 返回数据
    }

    function create_url($data)
    {
        $temp = '?';
        foreach ($data as $key => $item) {
            $temp = $temp . $key . '=' . $item . '&';
        }
        return substr($temp, 0, -1);
    }


}

